package com.ptszyxx.popose.module.main.mine;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.databinding.FragmentMineInviteBinding;
import com.ptszyxx.popose.module.main.mine.adapter.MineIncomeAdapter;
import com.ptszyxx.popose.module.main.mine.adapter.MineInviteRankAdapter;
import com.ptszyxx.popose.module.main.mine.vm.MineInviteVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.mine.InviteEntity;
import com.ysg.http.data.entity.mine.InviteIncomeEntity;
import com.ysg.http.data.entity.mine.InviteRankEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YPermissionUtil;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.InviteQrcodeDialog;
import com.ysg.widget.dialog.ShareDialog;

import java.util.List;

public class MineInViteFragment extends BaseFragment<FragmentMineInviteBinding, MineInviteVM> {
    public MineIncomeAdapter incomeAdapter;
    public MineIncomeAdapter personAdapter;
    public MineInviteRankAdapter rankAdapter;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_mine_invite;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MineInviteVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MineInviteVM.class);
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        incomeAdapter = new MineIncomeAdapter(viewModel);
        personAdapter = new MineIncomeAdapter(viewModel);
        rankAdapter = new MineInviteRankAdapter(viewModel);

        YRecyclerViewUtil.init(getActivity(), binding.recyclerIncome, incomeAdapter);
        YRecyclerViewUtil.init(getActivity(), binding.recyclerPerson, personAdapter);
        YRecyclerViewUtil.init(getActivity(), binding.recyclerRank, rankAdapter);
    }

    @Override
    public void initData() {
        super.initData();
        title = getResources().getString(R.string.mine_invite_share_title);
        content = getResources().getString(R.string.mine_invite_share_content);

        viewModel.requestInviteInfo();
        viewModel.requestInviteIncome();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onInviteInfoEvent.observe(this, o -> setInviteInfoUI((InviteEntity)o));
        viewModel.uc.onTabEvent.observe(this, o -> setTabUI((Integer) o));
        viewModel.uc.onIncomeEvent.observe(this, o -> setAdapterIncome((List<InviteIncomeEntity>) o));
        viewModel.uc.onPersonEvent.observe(this, o -> setAdapterPerson((List<InviteIncomeEntity>) o));
        viewModel.uc.onRankEvent.observe(this, o -> setAdapterRank((List<InviteRankEntity>) o));
        viewModel.uc.onShareEvent.observe(this, o -> shareDialogShare());
    }

    private void setAdapterIncome(List<InviteIncomeEntity> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            incomeAdapter.setList(list);
            binding.viewIncome.showContent();
        }else{
            binding.viewIncome.showEmpty();
        }
    }
    private void setAdapterPerson(List<InviteIncomeEntity> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            personAdapter.setList(list);
            binding.viewPerson.showContent();
        }else{
            binding.viewPerson.showEmpty();
        }
    }
    private void setAdapterRank(List<InviteRankEntity> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            rankAdapter.setList(list);
            binding.viewRank.showContent();
        }else{
            binding.viewRank.showEmpty();
        }
    }

    private void setInviteInfoUI(InviteEntity data) {
        if(YStringUtil.isNotEmpty(data.getYaoqingma() + "")){
            binding.tvInviteCode.setText(data.getYaoqingma());
        }
        if(YStringUtil.isNotEmpty(data.getSubordinatereward() + "")){
            String content = String.format(getResources().getString(R.string.mine_invite_reward_one), data.getSubordinatereward());
            binding.tvZhuanshi.setText(content);
        }
        if(YStringUtil.isNotEmpty(data.getGiftInvite() + "")){
            String content = String.format(getResources().getString(R.string.mine_invite_reward_two), (int)(data.getGiftInvite()*100) + "%");
            binding.tvGiftInvite.setText(content);
        }
        if(YStringUtil.isNotEmpty(data.getRechargeInvite() + "")){
            String content = String.format(getResources().getString(R.string.mine_invite_reward_three), (int)(data.getRechargeInvite()*100) + "%");
            binding.tvRechargeInvite.setText(content);
        }
    }

    public void setTabUI(int currentTab){
        binding.tvIncome.setTextColor(getResources().getColor(com.ysg.R.color.purpleLightColor));
        binding.tvInvitePeople.setTextColor(getResources().getColor(com.ysg.R.color.purpleLightColor));
        binding.tvRewardRank.setTextColor(getResources().getColor(com.ysg.R.color.purpleLightColor));
        binding.tvIncome.setBackground(null);
        binding.tvInvitePeople.setBackground(null);
        binding.tvRewardRank.setBackground(null);

        binding.viewIncome.setVisibility(View.GONE);
        binding.viewPerson.setVisibility(View.GONE);
        binding.viewRank.setVisibility(View.GONE);

        switch (currentTab){
            case 0:
                binding.tvIncome.setTextColor(getResources().getColor(com.ysg.R.color.black));
                binding.tvIncome.setBackgroundResource(com.ysg.R.drawable.shape_yellow_30);
                binding.viewIncome.setVisibility(View.VISIBLE);
                viewModel.requestInviteIncome();
                break;
            case 1:
                binding.tvInvitePeople.setTextColor(getResources().getColor(com.ysg.R.color.black));
                binding.tvInvitePeople.setBackgroundResource(com.ysg.R.drawable.shape_yellow_30);
                binding.viewPerson.setVisibility(View.VISIBLE);
                viewModel.requestInvitePeople();
                break;
            case 2:
                binding.tvRewardRank.setTextColor(getResources().getColor(com.ysg.R.color.black));
                binding.tvRewardRank.setBackgroundResource(com.ysg.R.drawable.shape_yellow_30);
                binding.viewRank.setVisibility(View.VISIBLE);
                viewModel.requestInviteRank();
                break;
        }
    }


    private String title;
    private String content;
    private void shareDialogShare() {
        YDialogUtil.getInstance().showShare(getContext()).setOnShareListener(new ShareDialog.OnShareListener() {
            @Override
            public void onWechatClick() {
                viewModel.wechatShare(0, title, content);
            }

            @Override
            public void onWechatFriendsClick() {
                viewModel.wechatShare(1, title, content);
            }

            @Override
            public void onQQClick() {
                viewModel.qqShare(getActivity(), title, content, getResources().getString(R.string.app_name));
            }

            @Override
            public void onQrcodeClick() {
                showDialogInviteQrcode();
            }
        });
    }

    private void showDialogInviteQrcode(){
        YDialogUtil.getInstance().showInviteQrcode(getContext()).setOnInviteQrcodeListener(new InviteQrcodeDialog.OnInviteQrcodeListener() {
            @Override
            public void onSaveClick() {
                onSaveQrcode();
            }
        });
    }

    private void onSaveQrcode(){
        YPermissionUtil.requestStorage(getActivity(), "申请存储权限：用于保存二维码图片",new YPermissionUtil.OnPermissionListener() {
            @Override
            public void onSuccess() {
                savePhotoToGallery(getContext(), drawableToBitmap(getContext().getResources().getDrawable(com.ysg.R.mipmap.invite_qr_code)));
            }

            @Override
            public void onError() {
            }
        });
    }

    /**
     * 将Bitmap图片保存到本地相册
     */
    public static void savePhotoToGallery(final Context context, final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 其次把文件插入到系统图库
                try {
                    String fileName = "invite_" + System.currentTimeMillis() + ".jpg";
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, fileName, ""); // 名字和描述没用，系统会自动更改
                    YToastUtil.showShortSafe( R.string.success);
                } catch (Exception e) {
                    e.printStackTrace();
                    YToastUtil.showShortSafe( R.string.fail);
                }
            }
        }).start();
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        return bitmapDrawable.getBitmap();
    }


}
